package u.hnx.admin.core;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import u.hnx.admin.query.user.LoginQuery;
import u.hnx.admin.security.api.LoginVerify;
import u.hnx.admin.security.api.SecurityPropertyAPI;
import u.hnx.admin.security.core.SecurityProperties;
import u.hnx.admin.support.redis.config.RedisCore;
import u.hnx.admin.utils.RequestContextHelper;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/*
创建人： 倔强的头发
创建时间：2024/6/22
功能描述: 登录错误验证,仿ruoyi

*/
@Component
@EnableConfigurationProperties(SecurityProperties.class)
public record LoginVerifyErrors(RedisCore redisCore, SecurityProperties securityProperties) implements LoginVerify,SecurityPropertyAPI {
    @Override
    public Integer getRetryCount(String cacheKey) {
        return Integer.parseInt(Optional.ofNullable(redisCore.getCache(cacheKey)).orElse("0"));
    }
    @Override
    public String getRetryKey(HttpServletRequest request) {
        LoginQuery loginQuery = RequestContextHelper.getContext();
        Optional.ofNullable(loginQuery).orElseThrow(()->new RuntimeException(PARAM_BLANK_ERROR));
        return Optional.ofNullable(loginQuery.getUsername()).map(n -> StrUtil.isNotBlank(n) ? StrUtil.join("", PWD_ERR_CNT_KEY, n) : "").get();
    }
    @Override
    public void setRetryCount(String cacheKey,Integer retryCount)  {
        redisCore.setCacheObject(cacheKey, ++retryCount, securityProperties.getLockTime(), TimeUnit.MINUTES);
    }
    @Override
    public boolean isRetry(Integer retryCount){
        return retryCount < securityProperties.getMaxRetryCount();
    }
    @Override
    public void clearLoginRecordCache(String loginName){
        if (redisCore.hasKey(loginName))
        {
            redisCore.deleteObject(loginName);
        }
    }
}
